import process from 'process'

export function getParameters(): any {
    const artifactsValue = process.env['TEMPLATE_PARAMETERS']
    let envVariables = extractParametersFromArtifactContent(artifactsValue)
    if (envVariables) {
        return envVariables
    } else {
        return false
    }
}

export function extractParametersFromArtifactContent(
    artifactsValue: string | undefined
): Map<string, string> {
    if (artifactsValue == undefined) {
        return new Map<string, string>()
    }

    let jsonValue = artifactsValue
    if (isBase64String(artifactsValue)) {
        jsonValue = decodeBas64String(artifactsValue)
    }
    return extractVariableFromJson(jsonValue)
}


function extractVariableFromJson(jsonDataStr: string): Map<string, string> {
    let result = new Map<string, string>()

    // 兼容 "" 的场景，否则 JSON.parse 会报错
    if (jsonDataStr.length == 0) {
        return result
    }

    let jsonData = JSON.parse(jsonDataStr)
    for (let key in jsonData) {
        let valueStr = jsonData[key] as string
        if (valueStr != 'custom' && valueStr != 'upstream') {
            result.set(key, valueStr)
        }
    }
    return result
}
function decodeBas64String(inputContent: string): string {
    let buff = Buffer.from(inputContent, 'base64')
    return buff.toString()
}

function isBase64String(inputContent: string): boolean {
    const base64regex =
        /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
    return base64regex.test(inputContent)
}